let express = require('express')

let router = express.Router()

let {
    conMysql
} = require('../mysql')

// 统一查询的响应函数
const sendResponse = (res, code, msg, data = {}, total = 0) => {
    res.send({
        code,
        msg,
        data,
        total
    });
};

// 查询数据库函数
const executeQuery = async (sql, params) => {
    try {
        return await conMysql(sql, params);
    } catch (error) {
        console.error("Database query error:", error);
        throw new Error('Database error');
    }
};


// 获取报警记录
router.get('/getAlarmRecord', async (req, res) => {
    const {
        startTime,
        endTime,
        pageSize,
        page
    } = req.query;
    delete req.query._t

    const limit = Number(pageSize);
    const offset = Number(pageSize * (page - 1));
    let sqlTotal, sql, params;

    if (!startTime) {
        sqlTotal = 'select count(0)  AS total FROM  history_alarms'
        sql = 'select * from history_alarms ORDER BY Time DESC  LIMIT ? OFFSET ?'
        params = [limit, offset]
    } else {
        sqlTotal = 'select count(0) AS total FROM  history_alarms WHERE Time BETWEEN ? AND ?'
        sql = 'select * from history_alarms WHERE Time BETWEEN ? AND ? ORDER BY Time DESC  LIMIT ? OFFSET ?'
        params = [startTime, endTime, limit, offset]
    }

    try {
        const [result, resultTotal] = await Promise.all([
            executeQuery(sql, params),
            executeQuery(sqlTotal, startTime ? [startTime, endTime] : [])
        ]);

        sendResponse(res, 0, 'success', result, resultTotal[0].total);
    } catch (error) {
        sendResponse(res, 1, 'Internal Server Error');
    }
})

// 获取斗轮堆取料机操作日志
router.get('/getBucketWheelStackerReclaimer', async (req, res) => {
    const {
        startTime,
        endTime,
        pageSize,
        page
    } = req.query;
    delete req.query._t;

    const limit = Number(pageSize);
    const offset = Number(pageSize * (page - 1));
    let sqlTotal, sql, params;

    if (!startTime) {
        sqlTotal = 'select count(0) AS total  from history_logs'
        sql = 'select * from history_logs ORDER BY Time DESC  LIMIT ? OFFSET ?'
        params = [limit, offset];
    } else {
        sqlTotal = 'select count(0)  AS total from history_logs WHERE Time BETWEEN ? AND ?'
        sql = 'select * from history_logs WHERE Time BETWEEN ? AND ? ORDER BY Time DESC  LIMIT ? OFFSET ?'
        params = [startTime, endTime, limit, offset];
    }
    try {
        const [result, resultTotal] = await Promise.all([
            executeQuery(sql, params),
            executeQuery(sqlTotal, startTime ? [startTime, endTime] : [])
        ]);

        sendResponse(res, 0, 'success', result, resultTotal[0].total);
    } catch (error) {
        sendResponse(res, 1, 'Internal Server Error');
    }
})

// 获取斗轮取料机操作日志
router.get('/getBucketWheelReclaimer', async (req, res) => {
    const {
        startTime,
        endTime,
        pageSize,
        page
    } = req.query;
    delete req.query._t;

    const limit = Number(pageSize);
    const offset = Number(pageSize * (page - 1));
    let sqlTotal, sql, params;
    if (!startTime) {
        sqlTotal = 'select count(0) AS total  from history_logs_two'
        sql = 'select * from history_logs_two ORDER BY Time DESC  LIMIT ? OFFSET ?'
        params = [limit, offset];
    } else {
        sqlTotal = 'select count(0) AS total  from history_logs_two WHERE Time BETWEEN ? AND ?'
        sql = 'select * from history_logs_two WHERE Time BETWEEN ? AND ? ORDER BY Time DESC  LIMIT ? OFFSET ?'
        params = [startTime, endTime, limit, offset];
    }

    try {
        const [result, resultTotal] = await Promise.all([
            executeQuery(sql, params),
            executeQuery(sqlTotal, startTime ? [startTime, endTime] : [])
        ]);

        sendResponse(res, 0, 'success', result, resultTotal[0].total);
    } catch (error) {
        sendResponse(res, 1, 'Internal Server Error');
    }
})

// 获取盘煤仪操作日志
router.get('/getCoalPanInstrument', async (req, res) => {
    const {
        startTime,
        endTime,
        pageSize,
        page
    } = req.query;
    delete req.query._t;

    const limit = Number(pageSize);
    const offset = Number(pageSize * (page - 1));
    let sqlTotal, sql, params;

    if (!startTime) {
        sqlTotal = 'select count(0) AS total  from history_logs_web'
        sql = 'select * from history_logs_web  ORDER BY Time DESC LIMIT ? OFFSET ?'
        params = [limit, offset];
    } else {
        sqlTotal = 'select count(0) AS total  from history_logs_web WHERE Time BETWEEN ? AND ?'
        sql = 'select * from history_logs_web WHERE Time BETWEEN ? AND ? ORDER BY Time DESC  LIMIT ? OFFSET ?'
        params = [startTime, endTime, limit, offset];
    }

    try {
        const [result, resultTotal] = await Promise.all([
            executeQuery(sql, params),
            executeQuery(sqlTotal, startTime ? [startTime, endTime] : [])
        ]);

        sendResponse(res, 0, 'success', result, resultTotal[0].total);
    } catch (error) {
        sendResponse(res, 1, 'Internal Server Error');
    }
})

// 获取分区密度
router.get('/getPartitionDensity', async (req, res) => {
    const {
        startTime,
        endTime,
        pageSize,
        page
    } = req.query;
    delete req.query._t;

    const limit = Number(pageSize);
    const offset = Number(pageSize * (page - 1));
    let sqlTotal, sql, params;

    if (!startTime) {
        sqlTotal = 'select count(0) AS total  from coal_yard_density'
        sql = 'select * from coal_yard_density ORDER BY Time DESC  LIMIT ? OFFSET ?'
        params = [limit, offset];
    } else {
        sqlTotal = 'select count(0) AS total  from coal_yard_density WHERE Time BETWEEN ? AND ?'
        sql = 'select * from coal_yard_density WHERE Time BETWEEN ? AND ? ORDER BY Time DESC  LIMIT ? OFFSET ?'
        params = [startTime, endTime, limit, offset];
    }

    try {
        const [result, resultTotal] = await Promise.all([
            executeQuery(sql, params),
            executeQuery(sqlTotal, startTime ? [startTime, endTime] : [])
        ]);

        sendResponse(res, 0, 'success', result, resultTotal[0].total);
    } catch (error) {
        sendResponse(res, 1, 'Internal Server Error');
    }
})

// 获取报表管理
router.get('/getReportManagement', async (req, res) => {
    const {
        startTime,
        endTime,
        pageSize,
        page
    } = req.query;
    delete req.query._t;

    const limit = Number(pageSize);
    const offset = Number(pageSize * (page - 1));
    let sqlTotal, sql, params;

    if (!startTime) {
        sqlTotal = 'SELECT COUNT(0) AS total  FROM history_report_name ';
        sql = 'SELECT * FROM history_report_name ORDER BY Time DESC LIMIT ? OFFSET ?';
        params = [limit, offset];
    } else {
        sqlTotal = 'SELECT COUNT(0) AS total  FROM history_report_name WHERE Time BETWEEN ? AND ? ';
        sql = 'SELECT * FROM history_report_name WHERE Time BETWEEN ? AND ? ORDER BY Time DESC LIMIT ? OFFSET ? ';
        params = [startTime, endTime, limit, offset];
    }

    try {
        const [result, resultTotal] = await Promise.all([
            executeQuery(sql, params),
            executeQuery(sqlTotal, startTime ? [startTime, endTime] : [])
        ]);

        sendResponse(res, 0, 'success', result, resultTotal[0].total);
    } catch (error) {
        sendResponse(res, 1, 'Internal Server Error');
    }
});

// 删除报表管理
router.delete('/deleteReportManagement', (req, res) => {
    let sql = `delete from history_report_name where ID = ? `
    let params = [req.body.id]
    if (!params) {
        return res.send({
            code: 1,
            msg: 'ID 不可为空'
        });
    }
    conMysql(sql, params).then(result => {
        let data = {
            code: 0,
            msg: '删除成功'
        }
        res.send(data)
    }).catch(err => {
        console.log(err)
        let data = {
            code: 1,
            msg: '删除失败'
        }
        res.send(data)
    })
})


module.exports = router